package com.xjrsoft.module.interfaceManager.controller;


import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xjrsoft.common.result.Response;
import com.xjrsoft.module.interfaceManager.dto.AddInfoDto;
import com.xjrsoft.module.interfaceManager.dto.AuthDto;
import com.xjrsoft.module.interfaceManager.entity.XjrInterfaceAuth;
import com.xjrsoft.module.interfaceManager.service.IXjrInterfaceAuthService;
import com.xjrsoft.module.interfaceManager.service.IXjrInterfaceInfoService;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 接口权限表 前端控制器
 * </p>
 *
 * @author tzx
 * @since 2022-04-22
 */
@RestController
@RequestMapping("/interface-auth")
@AllArgsConstructor
public class XjrInterfaceAuthController {

    private final IXjrInterfaceAuthService authService;

    @PostMapping
    @ApiOperation(value="新增接口管理")
    @Transactional
    public Response<Boolean> add(@RequestBody AuthDto authDto) {
        String objectId = authDto.getObjectId();
        Integer objectType = authDto.getObjectType();
        List<String> idList = authDto.getIdList();
        // 删除原有数据
        Wrapper<XjrInterfaceAuth> deleteWrapper = Wrappers.<XjrInterfaceAuth>query().lambda()
                .eq(XjrInterfaceAuth::getObjectId, objectId)
                .eq(XjrInterfaceAuth::getObjectType, objectType);
        authService.remove(deleteWrapper);
        List<XjrInterfaceAuth> savedList = new ArrayList<>();
        for (String id : idList) {
            XjrInterfaceAuth auth = new XjrInterfaceAuth();
            auth.setInfoId(id);
            auth.setObjectId(objectId);
            auth.setObjectType(objectType);
            savedList.add(auth);
        }
        return Response.ok(authService.saveBatch(savedList));
    }

    @GetMapping("/{objectId}/{objectType}/auths")
    @ApiOperation(value="获取当前用户的授权的接口")
    public Response<List<String>> getAuthsOfObject(@PathVariable String objectId, @PathVariable Integer objectType) {
        return Response.ok(authService.getAuthIdsOfObject(objectId, objectType));
    }
}
